use std::{
    fs::File,
    io::{BufReader, Write},
    path::Path,
};

use serde::{Deserialize, Serialize};

// 代码生成期的一些设置，多用于编译优化
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AsmCodeGenSettings {
    pub eval_constant_expression: bool, // 常量表达式编译期求值
    pub reduce_unary: bool,             // 尝试对一元操作符进行进一步的归约
}

impl Default for AsmCodeGenSettings {
    fn default() -> Self {
        AsmCodeGenSettings {
            eval_constant_expression: true,
            reduce_unary: true,
        }
    }
}

pub fn save_current_settings(p: &Path, settings: &AsmCodeGenSettings) -> std::io::Result<()> {
    let mut f = File::create(p)?;
    f.write_all(serde_json::to_string_pretty(settings)?.as_bytes())?;
    Ok(())
}

pub fn read_settings(p: &Path) -> std::io::Result<AsmCodeGenSettings> {
    let f = File::open(p)?;
    let reader = BufReader::new(f);
    let s: AsmCodeGenSettings = serde_json::from_reader(reader)?;
    Ok(s)
}
